package com.lishangshan.oas_system.controller.user;

import com.github.pagehelper.util.StringUtil;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.lishangshan.oas_system.model.dao.user.PositionDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.dao.user.UserLogRecordDao;
import com.lishangshan.oas_system.model.entity.role.Role;
import com.lishangshan.oas_system.model.entity.user.Dept;
import com.lishangshan.oas_system.model.entity.user.LoginRecord;
import com.lishangshan.oas_system.model.entity.user.Position;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 用户 管理 控制器
 */
@Controller
@RequestMapping("/")
public class UserController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserControllerFun userControllerFun;

    /**
     * 初始化 用户 管理 界面
     *
     * @param page
     * @return
     */

    @RequestMapping("usermanage")
    public ModelAndView userIndex(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page) {
        ModelAndView view = new ModelAndView("user/usermanage");
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
        Page<User> userPage = userDao.findAll(pa);
        view.addObject("page", userPage);
        view.addObject("users", userPage.getContent());
        view.addObject("url", "usermanagepaging");
        return view;
    }

    /**
     * 用户 管理 界面 上一页 下一页 控制器
     *
     * @param page
     * @return
     */
    @RequestMapping("usermanagepaging")
    public String usermanagepaging(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model
            , @RequestParam(value = "usersearch", required = false) String usersearch) {
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
        Page<User> userspage = null;
        if (StringUtil.isEmpty(usersearch)) {
            userspage = userDao.findByIsLock(0, pa);
        } else {
            userspage = userDao.findnamelike(usersearch, pa);
        }
        System.out.println(userspage.getContent());
        model.addAttribute("users", userspage.getContent());
        model.addAttribute("page", userspage);
        model.addAttribute("url", "usermanagepaging");
        return "user/usermanagepaging";
    }


    /**
     * 跳转 添加 或 修改  页面
     *
     * @return
     */
    // useredit
    @RequestMapping("useredit")
    public String toUseredit(@RequestParam(value = "userid", defaultValue = ParameterUtil.ROLE_DEFLUT) Long userid, Model model) {
        userControllerFun.findSession(model);
        if (userid == -1) {
            System.out.println("我是去添加");
        } else {
            User one = userDao.findOne(userid);
            model.addAttribute("user", one);
            model.addAttribute("where", one);
        }
        return "user/edituser";
    }

    private Dept dept = new Dept();
    private Role role = new Role();
    private Position position = new Position();

    /**
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("usersave")
    public String save(User user, Model model, HttpServletRequest req) throws PinyinException {
        Long deptid = Long.parseLong(req.getParameter("deptid"));
        Long positionid = Long.parseLong(req.getParameter("positionid"));
        Long roleid = Long.parseLong(req.getParameter("roleid"));
        dept.setDeptId(deptid);
        role.setRoleId(roleid);
        position.setId(positionid);
        // 用户名转拼音 并设置 拼音
        String pinyin = PinyinHelper.convertToPinyinString(user.getUserName(),"", PinyinFormat.WITHOUT_TONE);
        user.setPinyin(pinyin);
        // 获取前台 复选框 状态判断是否被选中
        String isbackpassword = req.getParameter("isbackpassword");
        if (user.getUserId() == null) {
            // 执行添加 或者 重置密码时都要重置密码
            user.setPassword("123456");
        }
      /*  if (user.getUserId() == null) {
            user.setPassword("123456"); //设置默认密码
        }*/
        // 如果 用户id不为空时,查询修改前的属性值并赋值部分
        if (user.getUserId() != null) {
            User one = userDao.findOne(user.getUserId());
            //设置最后修改时间
            user.setModifyTime(new Date());
            user.setImgPath(one.getImgPath()); // 设置原有头像
            user.setUserSign(one.getUserSign()); // 设置原有的
            user.setPinyin(one.getPinyin()); // 设置原有拼音
            user.setHireTime(one.getHireTime());//设置入职时间
            if (isbackpassword != null) {
                // 执行添加 或者 重置密码时都要重置密码
                user.setPassword("123456");
            } else {
                user.setPassword(one.getPassword()); //设置原密码
            }
        }
        //三个外建 关联
        user.setPosition(position);
        user.setRole(role);
        user.setDept(dept);
        System.out.println("前台 传送 数据=" + user);
        User save = userDao.save(user);
        return "forward:/usermanage";
    }

    @Autowired
    private PositionDao positionDao;

    //    useronlyname
    @RequestMapping("/useronlyname")
    @ResponseBody
    public Boolean useronlyname(@RequestParam("username") String username) {
        User user = userDao.findByUserName(username);
        System.out.println("唯一验证 = " + user);
        if (user != null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 下拉菜单 联动处理
     *
     * @return
     */
    //selectdept
    @RequestMapping("/selectdept")
    @ResponseBody
    public List<Position> selectdept(@RequestParam(value = "selectdeptid") long selectdeptid) {
        List<Position> positions = positionDao.findByDeptid(selectdeptid);
        return positions;
    }

    /**
     * 用户 删除
     *
     * @param userid
     * @return
     */
    //    deleteuser
    @RequestMapping("/deleteuser")
    public String deleteuser(@RequestParam("userid") Long userid) {
        try {
            userDao.delete(userid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forward:/usermanage";
    }

    @Autowired
    private UserLogRecordDao userLogRecordDao;

    /**
     * 初始化 在线人数 页面
     *
     * @param page
     * @return
     */
    // morelogrecord
    @RequestMapping("/morelogrecord")
    public ModelAndView morelogrecord(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page) {
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
        ModelAndView view = new ModelAndView("user/userlogrecordmanage");
        Page<LoginRecord> recordPage = userLogRecordDao.findAll(pa);
        view.addObject("page", recordPage);
        view.addObject("userloglist", recordPage.getContent());
        view.addObject("url", "userLogRecordPading");
        return view;
    }

    /**
     * 在线用户  分页 查找
     *
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("/userLogRecordPading")
    public String userLogRecordPading(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                                      Model model, @RequestParam(value = "baseKey", defaultValue = ParameterUtil.ROLE_DEFLUT) String baseKey
            , @SessionAttribute("userId") Long userId) {
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
        Page<LoginRecord> recordPage = null;
        System.out.println("baseKey" + baseKey);
        // 根据 basekey 来当用户名 去查找 用户 id
        User byUserName = userDao.findByUserName(baseKey);
        if ("-1".equals(baseKey)) {
            recordPage = userLogRecordDao.findAll(pa);
        } else {
            recordPage = userLogRecordDao.findbasekey(userId, baseKey, pa);
        }
        //明天要修改
        model.addAttribute("page", recordPage);
        model.addAttribute("userloglist", recordPage.getContent());
        model.addAttribute("url", "userLogRecordPading");
        return "user/userlogrecordmanagetable";
    }
}
